import { useState } from 'react'
import { cardList, cardEnum } from '../index'
import { useNavigate } from 'react-router-dom'
import { useStatesContext, getInitStream } from '../index'
function SvgIcon({ svgString }: { svgString: string }): React.JSX.Element {
  return <div className="svg-icon" dangerouslySetInnerHTML={{ __html: svgString }} />
}
function Index(): React.JSX.Element {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const states = useStatesContext()
  const handleClick = (item: { key: string }): undefined => {
    console.log('loading', loading)
    if (loading) return
    setLoading(true)
    window.electron.ipcRenderer.invoke('capture', cardEnum[item.key]).then(async (response) => {
      // 返回的东西
      console.log(response)
      const { success, error, result } = response
      if (success === true) {
        // 等待这个功能完成
        if (item.key === 'recording') {
          // 跳转到选择视频源界面
          const windowScreenSource = await Promise.all(
            result.map(async (item) => {
              const stream = await getInitStream(item)
              if (!stream)
                return {
                  ...item,
                  base64: ''
                }
              const cb = (stream): Promise<string> => {
                return new Promise((resolve, reject) => {
                  const videoNode = document.createElement('video') as HTMLVideoElement
                  videoNode.srcObject = stream
                  videoNode.onloadedmetadata = () => {
                    videoNode.play()
                    // 生成缩略图
                    const canvas = document.createElement('canvas')
                    canvas.width = videoNode.videoWidth
                    canvas.height = videoNode.videoHeight
                    canvas?.getContext('2d')?.drawImage(videoNode, 0, 0)
                    stream.getTracks().forEach((track) => track.stop())
                    resolve(canvas.toDataURL('image/png'))
                  }
                  videoNode.onerror = () => {
                    reject('????')
                  }
                })
              }
              const base64 = await cb(stream)
              console.log('stream', stream)
              return {
                ...item,
                base64,
                stream
              }
            })
          )
          states.setStates((pre) => ({ ...pre, windowScreenSource }))
          navigate('/selectVideoSource')
        }
        // 录像
        if (item.key === 'video') {
          const devices = await navigator.mediaDevices.enumerateDevices()
          console.log('devices', devices)
          const videoDevices = devices.filter((device) => device.kind === 'videoinput')
          console.log('videoDevices', videoDevices)
          const videoDevice = videoDevices[0]
          if (!videoDevice) {
            console.log('没有视频设备')
            return
          }
          window.electron.ipcRenderer.send(
            'open:recording:video',
            JSON.stringify({
              type: 'camera',
              devices: videoDevice
            })
          )
          // window.electron.ipcRenderer.send('open:recording:video', result)
        }
        if (item.key === 'viewFile') {
          window.electron.ipcRenderer.send('open-serachFile-win')
        }
      } else {
        console.log(error)
      }
      setLoading(false)
    })
  }
  const handleMore = (_, item): void => {
    _.stopPropagation()
    // 打开 setting 窗口
    window.electron.ipcRenderer.send('open:setting:win', item)
  }

  return (
    <>
      <div className="container">
        <div className="container-card-warp">
          {cardList.map((item) => (
            <div key={item.key} className="main-card" onClick={() => handleClick(item)}>
              <p>{item.text}</p>
              {<SvgIcon svgString={item.icon}></SvgIcon>}
              {!item.noSetting && (
                <div className="main-card-more" onClick={(event) => handleMore(event, item)}>
                  <svg
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    width="13"
                    height="13"
                  >
                    <path
                      d="M66.488889 211.781818h891.022222c28.198788 0 50.980202-22.238384 50.980202-49.648485 0-27.397172-22.768485-49.648485-50.980202-49.648485H66.488889C38.341818 112.484848 15.508687 134.723232 15.508687 162.133333s22.833131 49.648485 50.980202 49.648485z m891.009293 248.242424H66.488889C38.277172 460.024242 15.508687 482.262626 15.508687 509.672727s22.768485 49.648485 50.980202 49.648485h891.022222c28.198788 0 50.980202-22.238384 50.980202-49.648485-0.012929-27.410101-22.923636-49.648485-50.993131-49.648485z m0 351.63798H66.488889c-28.134141 0-50.980202 22.238384-50.980202 49.648485s22.833131 49.648485 50.980202 49.648485h891.022222c28.198788 0 50.980202-22.238384 50.980202-49.648485-0.012929-27.397172-22.781414-49.648485-50.993131-49.648485z m0 0"
                      fill="#8a8a8a"
                    ></path>
                  </svg>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </>
  )
}
export default Index
